$(document).ready(function(){
	$('.editMemberChangePassword').hide();
	$('#tab_content_page').hide();

	var numberOfMembers = 15;
	var page = 0;
	var timeOutTime = 5000;
	var oldPrivs = '';
	
	
	// used for module select change event
	var selectedMemberID = 1;
	
	initControls();
	
	// this is synchronous function, so it must runs after initControl
	var isAdmin = checkAdmin();	
	
	shouldCreatePrivHeader();
	shouldCreateNewButton();
	loadMember();
	
	//////////////////////////// Init controls /////////////////////////////////////////////////////////
	function initControls()
	{				
		initNewMemberDialog();
		initEditMemberDialog();
		initRemoveMemberDialog();
		initLoadingDialog();		
		initBackButton();
		initSubmitButton();
		initModuleSelect();
	} // end initControl function
	

	
	function shouldCreatePrivHeader()
	{
		// Add permission granting to admin
		if(isAdmin) {
			$('#listMemberTable thead tr').append('<th>Quyền</th>');
		}
	}

	function shouldCreateNewButton()
	{		
		$('#newMemberButtonWrapper').remove();		
		if(isAdmin) {
			var newButtonHTML = '<div id="newMemberButtonWrapper" style="padding: 0 0 5px 0;"><input id="newMemberButton" type="button" value="Thêm mới" /></div>';						
			
			// add it to tab content
			$('#tab_content').prepend(newButtonHTML);
			
			// add UI
			$('#newMemberButton').button();
			
			// add new event handler
			$("#newMemberButton").click(function(){
				newMember();		
			});			
		}
	} // end shouldCreateNewButton function

	function loadMember()
	{
		$.get("/member/list", 
			  {from: page * numberOfMembers, number: numberOfMembers, isAdmin: isAdmin}, 
			  function(data){					
				  	var returnData = $.parseJSON(data);
					$('#listMemberTable tbody').remove();
					
					var memberTableHTML = '<tbody>';
					for (var i = 0; i < returnData.data.length; i++)
					{
						memberTableHTML += "<tr>";
						memberTableHTML += '<td class="memberIDTd">' + returnData.data[i].ID + "</td>";
						memberTableHTML += '<td class="fullNameTd">' + returnData.data[i].FULLNAME + "</td>";
						memberTableHTML += '<td>' + returnData.data[i].EMAIL + "</td>";
						memberTableHTML += '<td class="isAdminTd">' + returnData.data[i].IS_ADMIN + "</td>";
						memberTableHTML += '<td class="isActiveTd">' + returnData.data[i].IS_ACTIVE + "</td>";
						memberTableHTML += '<td class="functionTd">' +
								"<a href='#' class='editMember'>Sửa</a>";
						memberTableHTML += (isAdmin ? ' | <a href="#" class="removeMember">Xóa</a>' : '');												
						memberTableHTML += '</td>';						
						memberTableHTML += (isAdmin ? '<td class="privTd"><a href="#" class="editPriv">Sửa</a></td>' : '');						
						memberTableHTML += '</tr>';
					}		
					memberTableHTML += '</tbody>';
					$('#listMemberTable').append(memberTableHTML);
					
					// Edit member event handler
					$(".editMember").click(function(){
						var memberID = $(this).parent('td').parent('tr').find('.memberIDTd').text();
						editMember(memberID);
						return false;
					});
					// Remove member event handler
					$(".removeMember").click(function(){
						var memberID = $(this).parent('td').parent('tr').find('.memberIDTd').text();
						removeMember(memberID);
						return false;
					});
					
					$(".editPriv").click(function(){
						$('#tab_content').slideUp(function() {
							$('#tab_content_page').fadeIn();
						});	
						selectedMemberID = $(this).parent('td').parent('tr').find('.memberIDTd').text();
						var memberFullName = $(this).parent('td').parent('tr').find('.fullNameTd').text();						
						editPriv(memberFullName);							
					});
					
					// init quick tips for edit and remove links
					quickTip();
			} // end success function
		); // end $.get function
	} // end loadMember function
	
	//////////////////////////// Event helpers /////////////////////////////
	function newMember()
	{
		$("#newMemberErrorRow").css("display", "none");
		$('#newMemberFullName').val('');
		$('#newMemberPassword').val('');
		$('#newMemberPasswordConfirm').val('');
		$('#newMemberEmail').val('');
		$("#newMemberDialog").dialog("open");
	}
	function editMember(memberID)
	{		
		if (memberID > 0)
		{
			$.get("/member/get-info", {id: memberID}, function(data){
				var returnData = $.parseJSON(data);
				if (returnData.code == 0)
				{
					$("#editMemberErrorRow").css("display", "none");
					$("#editMemberFullName").val(returnData.data.FULLNAME);
					$("#editMemberEmail").val(returnData.data.EMAIL);
											
					// store edited member ID
					$("#editMemberID").val(returnData.data.ID);	
					
					// clear  current password field
					$('#editMemberCurrentPassword').val('');
					
					// open edit dialog
					$("#editMemberDialog").dialog("open");
					
					if(isAdmin == 0) {
						$('#editMemberPasswordBool').change(function(){
							var b = $('#editMemberPasswordBool').is(':checked');						
							if(b) {
								$('.editMemberChangePassword').fadeIn();
							} else {
								$('.editMemberChangePassword').fadeOut();
							}
						});
						
						// hide isAdmin checkbox
						$('#editMemberIsAdminWrapper').hide();
						
						// hide isActive checkbox
						$('#editMemberIsActiveWrapper').hide();
					} else {
						$('#editMemberCurrentPasswordWrapper').hide();
						$('#editMemberPasswordBool').change(function(){
							var b = $('#editMemberPasswordBool').is(':checked');						
							if(b) {							
								$('#editMemberNewPasswordWrapper').fadeIn();
								$('#editMemberNewPasswordConfirmWrapper').fadeIn();
							} else {							
								$('#editMemberNewPasswordWrapper').fadeOut();
								$('#editMemberNewPasswordConfirmWrapper').fadeOut();
							}
						});

						if (returnData.data.IS_ADMIN)
							$("#editMemberIsAdmin").attr("checked", "checked");
						else
							$("#editMemberIsAdmin").removeAttr("checked");
							
						if (returnData.data.IS_ACTIVE)
							$("#editMemberIsActive").attr("checked", "checked");
						else
							$("#editMemberIsActive").removeAttr("checked");						
					}			

				}
			});
		}
	}
	function removeMember(memberID)
	{
		if (memberID > 0)
		{	
			$("#removeShowMemberID").html(memberID);
			$("#removeMemberID").val(memberID);
			$("#removeMemberDialog").dialog("open");
		}
	}

	function editPriv(memberFullName)
	{			
		if(selectedMemberID > 0) {
			// store memberID
			$('#privMemberID').val(selectedMemberID);			
			$('#memberNameSpan').html(memberFullName);
			
			// reset all privileges checkboxes
			resetPrivileges();
			
			// remove all privReport children
			$('#privReport').empty();
			
			// reset moduleSelect to 'news'
			$('#moduleSelect').val('news');
			
			// call change event
			$('#moduleSelect').change();

			$('#pageBorder').hide();			
		}
	}
	

	
	
	
	//////////////////////////////////////// Quick tips //////////////////////////////////////
	function quickTip()
	{
		$(".editMember").qtip({
			content: "Sửa nhân viên",
			show: {when: {event: "mouseover"}},
			hide: {when: {event: "mouseout"}},
			style: {
				name: "cream",
				border: {
					width: 2,
					radius: 3
				}
			},
			position: {
				corner: {
					target: 'leftMiddle',
					tooltip: 'rightMiddle'
				}
			}
		});
		$(".removeMember").qtip({
			content: "Xóa nhân viên",
			show: {when: {event: "mouseover"}},
			hide: {when: {event: "mouseout"}},
			style: {
				name: "cream",
				border: {
					width: 2,
					radius: 3
				}
			},
			position: {
				corner: {
					target: 'leftMiddle',
					tooltip: 'rightMiddle'
				}
			}
		});
	} // end quickTip function
	
	////////////////// Helpers //////////////////////
	function checkAdmin()
	{
		var isAdmin = 0;
		$.ajax({
			url: '/member/check-admin',
			async: false,
			success: function(data){
				var returnData = $.parseJSON(data);
				isAdmin = returnData.isAdmin;			
			}
		});
		return isAdmin;
	} // end checkAdmin function
	
	function showLoadingDialog()
	{
		$(".ui-dialog-titlebar").hide(); // hide title bar
		$('#loadingDialog').dialog('open');		
	}
	
	function hideLoadingDialog()
	{
		$(".ui-dialog-titlebar").show(); // hide title bar
		$('#loadingDialog').dialog('close');
	}

	function resetPrivileges()
	{
		$('#selectPrivCheckBox').attr('checked', false);
		$('#insertPrivCheckBox').attr('checked', false);
		$('#updatePrivCheckBox').attr('checked', false);
		$('#deletePrivCheckBox').attr('checked', false);	
	}
	
	
	//////////////////////////// Init functions ////////////////////////////////////////////////////
	function initNewMemberDialog()
	{
		///////////////////// new member dialog /////////////////////
		$("#newMemberDialog").dialog({
			autoOpen: false,
			width: 300,
			resizable: false,
			buttons: {
				"Thêm": function(){			
					$("#newMemberErrorRow").css("display", "none");
					$.post("/member/add", $("#newMemberForm").serialize(), function(data){						
						var returnData = $.parseJSON(data);					
						if (returnData.code == 0)
						{		
							loadMember();
							$('#newMemberDialog').dialog("close");
						}
						else
						{	
							$("#newMemberErrorRow").css("display", "");
							$("#newMemberErrorMessage").html(returnData.data);
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			},
			close: function(event, ui)
			{

			}
		}); // end new member dialog
	}
	
	function initEditMemberDialog()
	{
		///////////////////// Edit member dialog /////////////////////
		$("#editMemberDialog").dialog({
			autoOpen: false,
			width: 310,
			resizable: false,
			buttons: {
				"Cập nhật": function(){
					$("#editMemberErrorRow").css("display", "none");
					
					var paramString = $("#editMemberForm").serialize();
					paramString += ('&isAdmin=' + isAdmin);
					$.post("/member/edit", paramString, function(data){
						var returnData = $.parseJSON(data);
						if (returnData.code == 0)
						{	
							isAdmin = returnData.isAdmin;							
							shouldCreateNewButton();
							
							// if the edited user is the logged-in user, redraw the profile
							if(returnData.isMyself) {
								drawProfile();
							}
							
							loadMember();
							
							$('#editMemberDialog').dialog("close");					
						}
						else
						{
							$("#editMemberErrorRow").css("display", "");
							$("#editMemberErrorMessage").html(returnData.data);
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			},
			close: function(event, ui)
			{
				$('#editMemberPasswordBool').removeAttr('checked');
				$('.editMemberChangePassword').hide();
			}
		}); // end member dialog
	}
	
	function initRemoveMemberDialog()
	{
		///////////////////// Remove banner dialog /////////////////////
		$("#removeMemberDialog").dialog({
			autoOpen: false,
			width: 220,
			resizable: false,
			buttons: {
				"Xóa": function(){
					$.post("/member/remove", $("#removeMemberForm").serialize(), function(data){
						var returnData = $.parseJSON(data);
						if (returnData.code == 0)
						{
							// if the removed user is the logged-in user, force him to log out
							if(returnData.isMyself) {
								alert('Tài khoản này không còn nên sẽ được đăng xuất.');
								window.location.replace('/member/logout');
							} else {
								loadMember();
							}
							$("#removeMemberDialog").dialog("close");
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");					
				}
			}
		});	
	}
	
	function initLoadingDialog()
	{
		$('#loadingDialog').dialog({
			autoOpen: false,
			width: 100,
			height: 50,
			modal: true,
			resizable: false,
			draggable: false
		});
	}
	
	function initBackButton()
	{
		$('#backButton').button();
		$('#backButton').click(function(){
			$('#tab_content_page').fadeOut(function(){
				$('#tab_content').slideDown();
			});			
		});
	}
	
	function initSubmitButton()
	{
		$('#submitButton').button();		
		
		$('#submitButton').click(function(){
			selectedModule = $('#moduleSelect').val();
			
			// get serialized data
			var params;			
			if(selectedModule != 'page') {
				params = $('#privForm').serialize();				
			} else {
				params = $('#pageForm').serialize();				
				params += '&memberID=' + selectedMemberID;
			}
			params += '&module=' + selectedModule;			
						
			// remove all privReport children
			$('#privReport').empty();
						
			updatePrivileges(params + oldPrivs);
		});
	}
	
	////////////////////////////// Update privileges of all module ////////////////////////////
	function updatePrivileges(params)
	{
		// alert(params); return false;
		$.ajax({
			type: 'POST',
			url: '/privilege/update',
			data: params,
			timeOut: timeOutTime,
			beforeSend: function(data) {
				showLoadingDialog();
			},
			success: function(data) {
				hideLoadingDialog();
				var returnData = $.parseJSON(data);
				
				if(returnData.code == 0) {
					loadPagePrivileges(selectedMemberID);
					$('#privReport').append('<img src="/images/member/success.png" alt="success" width="30px" style="vertical-align: middle" height="30px"/>');
					$('#privReport').append(' <span style="vertical-align: middle">Cập nhật thành công</span>');
				} else {						
					$('#privReport').append('<img src="/images/member/failure.png" alt="failure" width="30px" style="vertical-align: middle" height="30px"/>');
					$('#privReport').append(' <span style="vertical-align: middle">' + returnData.data + '</span>');
				}
				$('#privReport').hide().fadeIn();
			},
			error: function(jqXHR, textStatus, errorThrown) {
				if(textStatus == 'timeout') {					
					updatePrivileges(params);
				}
			}
		});	
	}
	
	///////////////////////////////// Load privileges of module 'page' ///////////////////////////////////////
	function loadPagePrivileges(memberID)
	{
		$.ajax({
			type: 'GET',
			data: {id: memberID},
			url: '/privilege/get-page-privileges',
			timeout: timeOutTime,
			beforeSend: function(){
				showLoadingDialog();
			},			
			success: function(jsonObj) {
				hideLoadingDialog();
				var returnData = $.parseJSON(jsonObj);
				var data = returnData.data;
				if(returnData.code == 0) {
					var pageTableHTML = '';
					$('#pageTable tbody').remove();
					
					var pageTableHTML = '<tbody>';
					oldPrivs = '';
					for (var i = 0; i < data.length; i++)
					{
						pageTableHTML += '<tr>';
						pageTableHTML += '<td class="pageIDTd">' + data[i].ID + '</td>';
						pageTableHTML += '<td>' + data[i].NAME + '</td>';
						pageTableHTML += '<td class="pageFunctionTd">' +
						'Liệt kê <input name="np[' + data[i].ID + '][s]" value="' + 1 + '" type="checkbox"' + (data[i].SELECT_PRIV == 1 ? 'checked=checked' : '') + '"/> | ' +						
						'Sửa <input name="np[' + data[i].ID + '][u]" value="' + 1 + '" type="checkbox"' + (data[i].UPDATE_PRIV == 1 ? 'checked=checked' : '') + '"/> | ' +
						'Xóa <input name="np[' + data[i].ID + '][d]" value="' + 1 + '" type="checkbox"' + (data[i].DELETE_PRIV == 1 ? 'checked=checked' : '') + '"/>';
												
						if(data[i].SELECT_PRIV == 1) {							
							oldPrivs += encodeURI( '&op[' + data[i].ID + '][s]=1' );
						}						
						if(data[i].UPDATE_PRIV == 1) {							
							oldPrivs += encodeURI( '&op[' + data[i].ID + '][u]=1' );
						}
						if(data[i].DELETE_PRIV == 1) {							
							oldPrivs += encodeURI( '&op[' + data[i].ID + '][d]=1' );
						}
						
						pageTableHTML += '</td></tr>';
					}
					
					pageTableHTML += '</tbody>';
					$('#pageTable').append(pageTableHTML);
				}
			},
			error: function(jqXHR, textStatus, errorThrown){
				if(textStatus == 'timeout') {
					loadPagePrivileges(memberID);
				}
			}
		});
	}
	
	//////////////// Load priviges of module 'news' and 'banner' //////////////////////
	function loadPrivileges(memberID, module)
	{	
		$.ajax({
			type: "GET",
			url: '/privilege/get',
			data: {id: memberID, module: module},
			timeout: timeOutTime,
			beforeSend: function() {					
				showLoadingDialog();
			}, // end beforeSend function
			success: function(data) {					
				hideLoadingDialog();
				var returnData = $.parseJSON(data);
				if(returnData.code == 0) {
					$('#selectPrivCheckBox').attr('checked', returnData.data.SELECT_PRIV);
					$('#insertPrivCheckBox').attr('checked', returnData.data.INSERT_PRIV);
					$('#updatePrivCheckBox').attr('checked', returnData.data.UPDATE_PRIV);
					$('#deletePrivCheckBox').attr('checked', returnData.data.DELETE_PRIV);
				} else {
					alert('Có lỗi xảy ra');
					return false;
				}
			}, // end success function
			error: function(jqXHR, textStatus, errorThrown) {
				if(textStatus == 'timeout') {
					//alert('Làm ơn refresh');		
					loadPrivileges(memberID, module);
				}
			}
		});		
	}
	
	function initModuleSelect()
	{
		// add change event handler to moduleSelect
		$('#moduleSelect').change(function(){
			// remove all privReport children
			$('#privReport').empty();
			
			var module = $('#moduleSelect option:selected').val();
			
			if(module != 'page') {				
				$('#privBorder').show();				
				$('#pageBorder').hide();
				
				if(module == 'news' || module == 'banner') {
					// enable insert priv
					$('#insertPrivCheckBoxWrapper').show();			
				} else if(module == 'account') {
					// disable insert priv
					$('#insertPrivCheckBoxWrapper').hide();
				}
				
				loadPrivileges(selectedMemberID, module);	
			} else {
				$('#privBorder').hide();
				$('#pageBorder').show();
				
				loadPagePrivileges(selectedMemberID);		
			}
		});
	}
}); // end ready function
